/**
 * Created by fu.
 * Date: 12-1-31
 * Time: 上午11:46
 */

F.reg('drag/base',function(f,dom,event){
    var win = window,doc = win['document'],docElement = doc.documentElement;


    var dragdrop = new event.custom(),
        dragging = null,
        diffX = 0,
        diffY = 0,
        startoffset={},
        draggable='draggable';
    function preventdefault(e){
        e.prevent();
    }

    function handleEvent(e){

          var target = dom.query(e.target);
        //determine the type of event
        switch(e.type){
            case "mousedown":
                 if (target.hasclass(draggable)){
                    dragging = target;
                    event.add(dragging,'click',preventdefault);

                    startoffset = dragging.offset();
                    diffX = e.clientX - startoffset.l;
                    diffY = e.clientY - startoffset.t;
                    dragdrop.fire({type:"dragstart", target: dragging, x: e.clientX, y: e.clientY,startOffset:startoffset});
                    e.prevent();
                }
                break;

            case "mousemove":
                if (dragging !== null){

                     dragging.offset({l:e.clientX - diffX,t:e.clientY - diffY});
                     dragdrop.fire({type:"drag", target: dragging, x: e.clientX, y: e.clientY,startOffset:startoffset});
                     e.prevent();
                }

                break;

            case "mouseup":
                if(dragging){
                    dragdrop.fire({type:"dragend", target: dragging, x: e.clientX, y: e.clientY,startOffset:startoffset});
                    dragging = null;
                    e.prevent();
                }
                break;
        }

    }
    //public interface
    dragdrop.enable = function(draggableclass){
        draggableclass?draggable=draggableclass:0;

        event.add(document, "mousedown", handleEvent);
        event.add(document, "mousemove", handleEvent);
        event.add(document, "mouseup", handleEvent);
    };

    dragdrop.disable = function(draggableclass){
        if(dragging){
             event.del(dragging,'click',preventdefault);
        }
        event.del(document, "mousedown", handleEvent);
        event.del(document, "mousemove", handleEvent);
        event.del(document, "mouseup", handleEvent);
    };

    return dragdrop;

 },{
    requires:[
        'dom',
        'event'
    ]
});